package com.oreilly.ez.service.impl;

import com.oreilly.ez.base.BusinessException;
import com.oreilly.ez.entity.CourseTerm;
import com.oreilly.ez.entity.Enrollment;
import com.oreilly.ez.entity.Study;
import com.oreilly.ez.repo.StudyRepo;
import com.oreilly.ez.service.StudyService;
import com.oreilly.ez.util.CloneUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

@Service
public class StudyServiceImpl  implements StudyService{


    @Autowired
    private StudyRepo studyRepo;

    @Override
    public Study save(Study item) {

        CourseTerm courseTerm = item.getCourseTerm();

        Assert.notNull(courseTerm, "开课不能为空");
        Integer termSid = courseTerm.getSid();

        Enrollment enrollment = item.getEnrollment();
        Assert.notNull(courseTerm, "学生不能为空");
        Integer stuId = enrollment.getSid();

        Study dbStudy = studyRepo.findByStuIdAndTermId(stuId, termSid);
        if(dbStudy != null){
            throw  new BusinessException("不能重复选择开课");
        }

        // is update ??
        Integer sid = item.getSid();
        if(sid != null){
            Study dbItem = studyRepo.getOne(sid);

            CloneUtils.copyProperties(item, dbItem);
            CloneUtils.copyProperties(dbItem, item);

        }

        return studyRepo.save(item);

    }

    @Override
    public void remove(Integer sid) {

        studyRepo.deleteById(sid);
    }


    @Override
    public Page<Study> find(Study item, Pageable pageable) {

        return studyRepo.findAll(pageable);
    }

    @Override
    public List<Study> findByTermId(Integer termId) {

        return studyRepo.findByTermId(termId);
    }

    @Override
    public List<Study> findByStuId(Integer stuId) {
        return studyRepo.findByStuId(stuId);
    }

    @Override
    public Study findOne(Integer sid) {

        return studyRepo.findById(sid).get();
    }


}
